// API配置
const API_CONFIG = {
    url: 'https://api.siliconflow.cn/v1/chat/completions',
    token: 'xxx',
    model: 'Qwen/Qwen2.5-VL-32B-Instruct'
};

let selectedFiles = [];

// 文件选择处理
document.getElementById('fileInput').addEventListener('change', function(e) {
    selectedFiles = Array.from(e.target.files);
    updateImageList();
    updateTranslateButton();
    updateExportButton();
});

// 更新图片列表显示
function updateImageList() {
    const imageList = document.getElementById('imageList');
    
    if (selectedFiles.length === 0) {
        imageList.innerHTML = '<div class="empty-placeholder">请选择图片文件</div>';
        return;
    }

    imageList.innerHTML = '';
    selectedFiles.forEach((file, index) => {
        const imageItem = document.createElement('div');
        imageItem.className = 'image-item';
        imageItem.id = `image-${index}`;
        
        const img = document.createElement('img');
        img.src = URL.createObjectURL(file);
        img.alt = file.name;
        
        imageItem.appendChild(img);
        imageList.appendChild(imageItem);
    });

    // 同时更新结果列表
    updateResultList();
    // 更新导出按钮状态
    updateExportButton();
}

// 更新结果列表显示
function updateResultList() {
    const resultList = document.getElementById('resultList');
    
    if (selectedFiles.length === 0) {
        resultList.innerHTML = '<div class="empty-placeholder">翻译结果将在这里显示</div>';
        updateExportButton();
        return;
    }

    resultList.innerHTML = '';
    selectedFiles.forEach((file, index) => {
        const resultItem = document.createElement('div');
        resultItem.className = 'result-item';
        resultItem.id = `result-${index}`;
        resultItem.innerHTML = '<div class="loading">等待翻译...</div>';
        resultList.appendChild(resultItem);
    });
    updateExportButton();
}

// 更新翻译按钮状态
function updateTranslateButton() {
    const btn = document.getElementById('translateBtn');
    btn.disabled = selectedFiles.length === 0;
}

// 更新导出按钮状态
function updateExportButton() {
    const btn = document.getElementById('exportBtn');
    const hasResults = selectedFiles.length > 0 && 
                      document.querySelectorAll('.result-item.completed').length > 0;
    btn.disabled = !hasResults;
}

// 将文件转换为base64
function fileToBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
            const base64 = reader.result.split(',')[1];
            resolve(base64);
        };
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

// 调用API翻译图片
async function translateImage(base64Data) {
    const requestData = {
        model: API_CONFIG.model,
        messages: [
            {
                role: "user",
                content: [
                    {
                        type: "text",
                        text: "翻译图片中的文字为中文，只要结果，其他任何都不要输出"
                    },
                    {
                        type: "image_url",
                        image_url: {
                            url: `data:image/jpeg;base64,${base64Data}`
                        }
                    }
                ]
            }
        ]
    };

    const response = await fetch(API_CONFIG.url, {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${API_CONFIG.token}`,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
    });

    if (!response.ok) {
        throw new Error(`API请求失败: ${response.status}`);
    }

    const data = await response.json();
    
    if (data.choices && data.choices[0] && data.choices[0].message) {
        return data.choices[0].message.content;
    } else {
        throw new Error('API返回数据格式异常');
    }
}

// 开始翻译
async function startTranslation() {
    if (selectedFiles.length === 0) {
        alert('请先选择图片文件');
        return;
    }

    const translateBtn = document.getElementById('translateBtn');
    translateBtn.disabled = true;
    translateBtn.textContent = '翻译中...';

    for (let i = 0; i < selectedFiles.length; i++) {
        const file = selectedFiles[i];
        const resultElement = document.getElementById(`result-${i}`);
        
        try {
            // 更新状态为处理中
            resultElement.className = 'result-item processing';
            resultElement.innerHTML = '<div class="loading">正在翻译...</div>';
            
            // 转换为base64
            const base64Data = await fileToBase64(file);
            
            // 调用API翻译
            const result = await translateImage(base64Data);
            
            // 显示结果
            resultElement.className = 'result-item completed';
            resultElement.innerHTML = result;
            
            // 更新导出按钮状态
            updateExportButton();
            
        } catch (error) {
            // 显示错误
            resultElement.className = 'result-item error';
            resultElement.innerHTML = `翻译失败: ${error.message}`;
        }
        
        // 添加延迟避免API频率限制
        if (i < selectedFiles.length - 1) {
            await new Promise(resolve => setTimeout(resolve, 1000));
        }
    }

    // 恢复按钮状态
    translateBtn.disabled = false;
    translateBtn.textContent = '开始翻译';
}

// 导出结果为HTML
function exportResults() {
    const imageItems = document.querySelectorAll('.image-item img');
    const allResultItems = document.querySelectorAll('.result-item');

    if (imageItems.length === 0 || allResultItems.length === 0) {
        alert('没有可导出的翻译结果');
        return;
    }

    // 检查是否有完成的翻译
    const hasCompletedResults = document.querySelectorAll('.result-item.completed').length > 0;
    if (!hasCompletedResults) {
        alert('没有已完成的翻译结果');
        return;
    }

    let htmlContent = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片翻译结果</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background: #f5f5f5;
            padding: 20px;
            margin: 0;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .content-area {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        .panel {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .panel-title {
            font-weight: bold;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #007bff;
        }
        .image-list, .result-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        .image-item {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background: #f9f9f9;
            height: 400px;
        }
        .image-item img {
            width: 100%;
            height: 100%;
            object-fit: contain;
            border-radius: 4px;
        }
        .result-item {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            height: 400px;
            overflow-y: auto;
            display: flex;
            align-items: center;
        }
        .result-item.completed {
            background: #e8f5e8;
            border-color: #4caf50;
        }
        .result-item.error {
            background: #ffebee;
            border-color: #f44336;
        }
        .result-item.processing {
            background: #e3f2fd;
            border-color: #2196f3;
        }
        @media (max-width: 768px) {
            .content-area {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>图片翻译结果</h1>
            <p>生成时间：${new Date().toLocaleString()}</p>
        </div>
        <div class="content-area">
            <div class="panel">
                <div class="panel-title">原图</div>
                <div class="image-list">`;

    // 按索引添加图片和对应结果
    for (let i = 0; i < imageItems.length; i++) {
        const img = imageItems[i];
        const resultItem = allResultItems[i];

        // 添加图片
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        ctx.drawImage(img, 0, 0);
        const base64Data = canvas.toDataURL('image/png');

        htmlContent += `
                    <div class="image-item">
                        <img src="${base64Data}" alt="图片${i + 1}">
                    </div>`;
    }

    htmlContent += `
                </div>
            </div>
            <div class="panel">
                <div class="panel-title">翻译结果</div>
                <div class="result-list">`;

    // 按索引添加翻译结果
    for (let i = 0; i < allResultItems.length; i++) {
        const resultItem = allResultItems[i];
        const resultClass = resultItem.className;

        htmlContent += `
                    <div class="result-item ${resultClass.includes('completed') ? 'completed' : resultClass.includes('error') ? 'error' : 'processing'}">
                        ${resultItem.innerHTML}
                    </div>`;
    }

    htmlContent += `
                </div>
            </div>
        </div>
    </div>
</body>
</html>`;

    // 下载文件
    const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `图片翻译结果_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.html`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// 清空所有
function clearAll() {
    selectedFiles = [];
    document.getElementById('fileInput').value = '';
    updateImageList();
    updateTranslateButton();
    updateExportButton();
}

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    updateExportButton();
});
